package com.eqdd.yiqidian.ui.select;

import android.app.TimePickerDialog;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.text.TextUtils;
import android.view.View;

import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.SelectTimeActivityCustom;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarView;
import com.jakewharton.rxbinding.view.RxView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author吕志豪 .
 * @date 17-11-22  下午5:23.
 * Github :https://github.com/lvzhihao100
 * E-Mail：1030753080@qq.com
 * 简书 :http://www.jianshu.com/u/6e525b929aac
 */

public class SelectTimeActivity extends BaseActivity implements
        CalendarView.OnDateSelectedListener,
        CalendarView.OnDateChangeListener,
        View.OnClickListener {

    private SelectTimeActivityCustom dataBinding;
    private int mYear;
    private List<Calendar> schemes;
    private Calendar selectCarlendar;
    private int startYear;
    private int endYear;
    private boolean isFromToday;
    private Calendar calendarToday;

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_select_time);
        initTopTitleBar(View.VISIBLE, "日期区间选择");
        initTopRightText("确定", v -> {
            if (!TextUtils.isEmpty(dataBinding.tvStartDateFull.getText())) {
                String s = dataBinding.tvStartDateFull.getText().toString();
                s = s.replace("月", "-").replace("日", "");
                s = startYear + "-" + s;
                String e = dataBinding.tvEndDateFull.getText().toString();
                e = e.replace("月", "-").replace("日", "");
                e = endYear + "-" + e;
                Intent intent = new Intent();
                intent.putExtra(Config.START_TIME, s);
                intent.putExtra(Config.END_TIME, e);
                setResult(Config.SUCCESS, intent);
                finish();
            } else {
                ToastUtil.showShort("请选择时间");
            }
        });
    }

    @Override
    public void initData() {
        String title = getIntent().getStringExtra(Config.TITLE);
        if (title != null) {
            initTopTitleBar(View.VISIBLE, title);
        }
        isFromToday = getIntent().getBooleanExtra(Config.IS_FROM_TODAY, false);
        calendarToday = new Calendar();
        calendarToday.setDay(dataBinding.calendarView.getCurDay());
        calendarToday.setMonth(dataBinding.calendarView.getCurMonth());
        calendarToday.setYear(dataBinding.calendarView.getCurYear());

        dataBinding.tvMonthDay.setOnClickListener(v -> {
            dataBinding.calendarView.showSelectLayout(mYear);
            dataBinding.tvLunar.setVisibility(View.GONE);
            dataBinding.tvYear.setVisibility(View.GONE);
            dataBinding.tvMonthDay.setText(String.valueOf(mYear));
        });
        findViewById(R.id.fl_current).setOnClickListener(v -> dataBinding.calendarView.scrollToCurrent());

        dataBinding.calendarView.setOnDateChangeListener(this);
        dataBinding.calendarView.setOnDateSelectedListener(this);
        dataBinding.tvYear.setText(String.valueOf(dataBinding.calendarView.getCurYear()));
        mYear = dataBinding.calendarView.getCurYear();
        dataBinding.tvMonthDay.setText(dataBinding.calendarView.getCurMonth() + "月" + dataBinding.calendarView.getCurDay() + "日");
        dataBinding.tvLunar.setText("今日");
        dataBinding.tvCurrentDay.setText(String.valueOf(dataBinding.calendarView.getCurDay()));

    }

    @Override
    public void setView() {
        schemes = new ArrayList<>();
        dataBinding.calendarView.setSchemeDate(schemes);
        RxView.clicks(dataBinding.tvClear)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(aVoid -> {
                    schemes.clear();
                    dataBinding.calendarView.setSchemeDate(schemes);
                    dataBinding.tvDateStart.setText("");
                    dataBinding.tvStartDateFull.setText("");
                    dataBinding.tvDateEnd.setText("");
                    dataBinding.tvEndDateFull.setText("");
                    dataBinding.tvDateNum.setText("");

                });
        RxView.clicks(dataBinding.tvStartDateFull)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(aVoid -> {
                    if (!TextUtils.isEmpty(dataBinding.tvStartDateFull.getText())) {
                        new TimePickerDialog(SelectTimeActivity.this, (view, hourOfDay, minute) -> {
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
                            java.util.Calendar instance = java.util.Calendar.getInstance();
                            instance.set(java.util.Calendar.HOUR_OF_DAY, hourOfDay);
                            instance.set(java.util.Calendar.MINUTE, minute);
                            String format = simpleDateFormat.format(instance.getTime());
                            String s = dataBinding.tvStartDateFull.getText().toString();
                            String s1 = s.substring(0, s.indexOf(" ") + 1) + format;
                            dataBinding.tvStartDateFull.setText(s1);
                        }, 9, 0, true).show();
                    }
                });
        RxView.clicks(dataBinding.tvEndDateFull)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(aVoid -> {
                    if (!TextUtils.isEmpty(dataBinding.tvEndDateFull.getText())) {
                        new TimePickerDialog(SelectTimeActivity.this, (view, hourOfDay, minute) -> {
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
                            java.util.Calendar instance = java.util.Calendar.getInstance();
                            instance.set(java.util.Calendar.HOUR_OF_DAY, hourOfDay);
                            instance.set(java.util.Calendar.MINUTE, minute);
                            String format = simpleDateFormat.format(instance.getTime());
                            String s = dataBinding.tvEndDateFull.getText().toString();
                            String s1 = s.substring(0, s.indexOf(" ") + 1) + format;
                            dataBinding.tvEndDateFull.setText(s1);
                        }, 0, 0, true).show();
                    }
                });
    }

    private Calendar getSchemeCalendar(int year, int month, int day, int color, String text) {
        Calendar calendar = new Calendar();
        calendar.setYear(year);
        calendar.setMonth(month);
        calendar.setDay(day);
        calendar.setSchemeColor(color);//如果单独标记颜色、则会使用这个颜色
        calendar.setScheme(text);
        return calendar;
    }

    @Override
    public void onDateChange(Calendar calendar) {
        dataBinding.tvLunar.setVisibility(View.VISIBLE);
        dataBinding.tvYear.setVisibility(View.VISIBLE);
        dataBinding.tvMonthDay.setText(calendar.getMonth() + "月" + calendar.getDay() + "日");
        dataBinding.tvYear.setText(String.valueOf(calendar.getYear()));
        dataBinding.tvLunar.setText(calendar.getLunar());
        mYear = calendar.getYear();
    }

    private void updateSchemes() {
        Calendar minCalendar = schemes.size() == 0 ? selectCarlendar : schemes.get(0);
        Calendar maxCalendar = schemes.size() == 0 ? selectCarlendar : schemes.get(0);
        for (int i = 1; i < schemes.size(); i++) {
            if (isDateMax(maxCalendar, schemes.get(i))) {
                maxCalendar = schemes.get(i);
            }
            if (isDateMax(schemes.get(i), minCalendar)) {
                minCalendar = schemes.get(i);
            }
        }
        java.util.Calendar minCar = java.util.Calendar.getInstance();
        java.util.Calendar maxCar = java.util.Calendar.getInstance();
        if (isDateMax(selectCarlendar, minCalendar)) {
            minCar.set(selectCarlendar.getYear(), selectCarlendar.getMonth() - 1, selectCarlendar.getDay());
            maxCar.set(maxCalendar.getYear(), maxCalendar.getMonth() - 1, maxCalendar.getDay());
        } else {
            minCar.set(minCalendar.getYear(), minCalendar.getMonth() - 1, minCalendar.getDay());
            maxCar.set(selectCarlendar.getYear(), selectCarlendar.getMonth() - 1, selectCarlendar.getDay());
        }
        startYear = minCar.get(java.util.Calendar.YEAR);
        endYear = maxCar.get(java.util.Calendar.YEAR);
        java.util.Calendar dayCar = (java.util.Calendar) minCar.clone();
        schemes.clear();
        while (dayCar.compareTo(maxCar) <= 0) {
            schemes.add(getSchemeCalendar(dayCar.get(java.util.Calendar.YEAR),
                    dayCar.get(java.util.Calendar.MONTH) + 1,
                    dayCar.get(java.util.Calendar.DATE), 0, "记"));
            dayCar.add(java.util.Calendar.DATE, 1);
        }
        dataBinding.calendarView.setSchemeDate(schemes);
        updateTimeText(minCar, maxCar);

    }

    private void updateTimeText(java.util.Calendar minCar, java.util.Calendar maxCar) {
        int dayNum = (int) ((maxCar.getTimeInMillis() - minCar.getTimeInMillis()) / (1000 * 60 * 60 * 24)) + 1;
        SimpleDateFormat monthDaySf = new SimpleDateFormat("MM月dd日");
        String formatStart = monthDaySf.format(minCar.getTime());
        String formatEnd = monthDaySf.format(maxCar.getTime());
        dataBinding.tvStartDateFull.setText(formatStart + " 09:00");
        dataBinding.tvEndDateFull.setText(formatEnd + " 00:00");
        dataBinding.tvDateStart.setText(formatStart);
        dataBinding.tvDateEnd.setText(formatEnd);
        dataBinding.tvDateNum.setText("共" + dayNum + "天");
    }

    /**
     * @param min min
     * @param max max
     * @return
     */
    private boolean isDateMax(Calendar min, Calendar max) {
        java.util.Calendar minCar = java.util.Calendar.getInstance();
        minCar.set(min.getYear(), min.getMonth() - 1, min.getDay());
        java.util.Calendar maxCar = java.util.Calendar.getInstance();
        maxCar.set(max.getYear(), max.getMonth() - 1, max.getDay());
        return minCar.before(maxCar);
    }

    @Override
    public void onDateSelected(Calendar calendar) {
        if (!isDateMax(calendar, calendarToday)) {
            selectCarlendar = calendar;
            updateSchemes();
            onDateChange(calendar);
        } else {
            ToastUtil.showShort("选择的日期不合法");
        }
    }


    @Override
    public void onYearChange(int year) {
        dataBinding.tvMonthDay.setText(String.valueOf(year));
    }

}
